<?php

define( "COMMENT_SUBMITED",		0 );
define( "COMMENT_ACCESSDENIED",	1 );
define( "COMMENT_EMPTYBODY",	2 );
define( "COMMENT_ERROR",		3 );

$this->useClass("Handler_Comments");

class Action_Community_SubmitComment extends Handler_Comments
{
	var $ajax_functions = array(
	'ajax_submit_comment'
	);

	private function submit_comment( $item_oid, $parent_oid, $cbody ) {

		$aa = &$this->aa;
		$aa->getAvailableOperations($item_oid);
		// 1. проверим права
		if	(!$aa->is_granted(array('comment_create_premod', 'comment_create')) ) {
			return COMMENT_ACCESSDENIED;
		}

		// 2. проверим не пустое ли тело нам прислали
		if ( trim($cbody)=="" ) {
			return COMMENT_EMPTYBODY;
		}

		if ($parent_oid == 0) {
			$obj = $this->submitCommentOnItem($item_oid, $cbody);
			$parent_oid = $item_oid;
		} else {
			$obj = $this->submitCommentOnComment($item_oid, $parent_oid, $cbody);
		}

		$this->objid = $obj->id;

		// --- acl --- {{{
		// прописывает в субъекты и в acl
		$aa->createComment( $obj->id, $parent_oid );

		// для автора права
		$aa->setAcl($obj->id, array(
		'comment_edit'   => 1,
		'comment_delete' => 1,
		));

		// --- acl --- }}}

		// --- email notification --- {{{
		$mail_data = $aa->template_data;
		$mail_data['service'] = array('name'=>'Platonica');
		//$mail_data['section'] = $tdis[ $form->hash['tdi_oid']->model->model_data ];
		$mail_data['post'] = $this->ctx->store->find('select objects where oid = :0', array($item_oid))->next();
		$mail_data['comment'] = $obj;
		$mail_data['poster']['data'] = $aa->acl_data['user'];
		$mail_data['poster']['id'] = $aa->acl_data['user']['user_id'];
		require_once 'includes/workaholic.php';
		Workaholic::addTask(array($this, 'notifyEmail'), $mail_data);

		$parentComment = $this->getOneComment($parent_oid);

		if ( isset($parentComment) && isset($parentComment['posted_by_id'])
		&& isset($obj->data['posted_by_id'])
		&& $obj->data['posted_by_id'] != $parentComment['posted_by_id'] ) {
			$this->rh->UseClass("Model_User");
			$m_user = new Model_User( $this->rh, $this->aa);
			$mail_data['post']->parent = $m_user->getUser($parentComment['posted_by_id']);
		}

		Workaholic::addTask(array($this, 'notifyEmail'), $mail_data);

		//$this->notifyEmail($mail_data);
		// --- email notification --- }}}
		if (!$this->ctx->db->isErrorInTransaction()) {
			return COMMENT_SUBMITED;

		} else {
			$this->ctx->db->rollback();
			return COMMENT_ERROR;
		}
	}

	/**
	 * Добавить комментарий
	 *
	 * @param $item_oid - int oid итема
	 * @param $parent_oid - int oid родительского объекта, предполагается что это будет или комментарий или запись
	 * @param $cbody - string содержимое комментария
	 * @return int - код ошибки
	 * @author Alexander Sibiryakov
	 **/
	public function ajax_submit_comment( $item_oid, $parent_oid, $cbody ) {
		$cp = &$this->rh->ctx->cp;
		$this->ctx->db->begin();
		$status = $this->submit_comment( $item_oid, $parent_oid, $cbody );
		$this->ctx->db->end();
		$nd_status = &$cp->add_node('status');
		$nd_status->set_data( $status );
		$nd_coid = &$cp->add_node( 'comment_oid' );
		$nd_coid->set_data( $this->objid );
		return $status;
	}

	protected function init() {
		parent::init();
		$this->rh->UseClass('RL_CyrDate');
		$this->aa = $this->module->aa;
		$this->ctx->db->begin();
		$this->aa->setItemOid( $this->rh->POST["item_oid"] );
		$this->aa->getInfo();
		$this->aa->getAvailableOperations();
	}

	protected function shutdown() {
		$this->ctx->db->end();
	}

	public function process ()
	{
		$this->aa->checkDeletions( array($this, "shutdown") );

		if (isset($this->rh->POST["isform"])) {
			// запускаем основную функцию сабмита если пришла форма
			$status = $this->submit_comment( $this->rh->POST["item_oid"], $this->rh->POST["parent_oid"], $this->rh->POST["comment"] );

			$view = $this->rh->views->findByName('after_submit_comment');
			$view->data = $this->aa->template_data;
			$view->data['status'] = $status;
			$view->data['community_url'] = $this->aa->acl_data['community_url'];
			$view->data['item_oid'] = $this->rh->POST["item_oid"];
		} else {
			echo "Форма не пришла.";
		}

		$this->rh->response->setContent($view);
	} // end of function process

	public function notifyEmail ($data)
	{
		$this->rh->UseClass("Model_MailOutbox");
		$outbox = new Model_MailOutbox( $this->rh, $this->aa);
		$outbox->template = 'email/new_comment.html';

		$this->rh->UseClass("Model_MailSubscriptions");
		$subscribers = new Model_MailSubscriptions ($this->rh, $this->aa);

		//$user = $this->ctx->store->find('select objects where user.oid = :0', array($this->aa->acl_data['user']['user_id']))->next();
		//$subscribers->subscribe($user, 0);

		$collect = $subscribers->selectNotifyComments($data['post']);

		$collect->each(array($this, 'post'), $data, $outbox);

		$outbox->delete_after_send = true;
		$outbox->list->select()->each(array($outbox, 'send'), $outbox->list);

		//var_dump($outbox->list->rs->sql);
	} // end of method notifyEmail

	public function post ($recipient, $message, $outbox)
	{
		$message['user'] = $recipient;
		$message['to'] = $recipient->data['email'];
		return $outbox->post($message);
	} // end of method post

}
